

function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(chart);

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const systolic = params[0];
        const diastolic = params[1];
        return `${systolic.name}<br/>
                收缩压: ${systolic.value}mmHg<br/>
                舒张压: ${diastolic.value}mmHg`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1/4', '1/24', '1/31', '2/4', '2/14', '2/18', '3/1'],
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#eee',
          type: 'dashed'
        }
      },
      axisLabel: {
        color: '#666'
      }
    },
    series: [
      {
        name: '收缩压',
        type: 'line',
        data: [92, 100, 110, 128, 140, 130, 90],
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#00CED1'
        },
        lineStyle: {
          color: '#00CED1',
          width: 3
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(0,206,209,0.3)'
            }, {
              offset: 1,
              color: 'rgba(0,206,209,0)'
            }]
          }
        }
      },
      {
        name: '舒张压',
        type: 'line',
        data: [58, 70, 63, 55, 50, 60, 90],
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#FFB6C1'
        },
        lineStyle: {
          color: '#FFB6C1',
          width: 3
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(255,182,193,0.3)'
            }, {
              offset: 1,
              color: 'rgba(255,182,193,0)'
            }]
          }
        }
      }
    ]
  };

  chart.setOption(option);
  return chart;
}
import request from '../../../../utils/request'
Page({
  data: {
    ec: {
      onInit: initChart
    },
    currentDate: '2021年3月1日 14:00',
    systolic: '120',
    diastolic: '80',
    pressureStatus: '正常',
    showModal: false,
    inputSystolic: '',
    inputDiastolic: '',
    pressureRecords: [
      {
        id: 1,
        date: '2020/01/24',
        time: '10:56',
        systolic: '120',
        diastolic: '89',
        status: '正常'
      }
    ]
  },

  onLoad: function() {
    // this.updateTime(); // 首次加载时获取并设置时间
    // // 设置一个定时器，每隔1秒更新一次时间
    // this.timer = setInterval(() => {
    //     this.updateTime();
    // }, 1000);

    this.getBloodPressure()
    .then(bloodPressure=>{
        this.setData({
            bloodPressure:bloodPressure
        })
    })
  },
  onUnload: function(){
    // 页面卸载时清除定时器，避免内存泄漏
    clearInterval(this.timer);
  },
  updateTime: function () {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

    this.setData({
        currentTime: formattedTime
    });
},
 //获取用户血压
 getBloodPressure(){
    return new Promise((resolve,reject)=>{
        let userId = wx.getStorageSync('userid')
        let bloodPressureid = 3  //数据库中血压id=3
        let url = `healthlog/healthlog/selectByUseridAndTypeid?userid=${userId}&typeid=${bloodPressureid}`
        request({
            url:url,
            method:'GET',
            success(res){
                let bloodPressure = res.data
                console.log("血压列表：",bloodPressure);
                resolve(bloodPressure)
            },fail(error){
                reject(error)
            }
        })
    })
  },
  goBack: function() {
    wx.navigateBack({
      delta: 1
    });
  },

  showPressureModal: function() {
    this.setData({
      showModal: true,
      inputSystolic: '',
      inputDiastolic: ''
    });
  },

  hideModal: function() {
    this.setData({
      showModal: false
    });
  },

  onSystolicInput: function(e) {
    this.setData({
      inputSystolic: e.detail.value
    });
  },

  onDiastolicInput: function(e) {
    this.setData({
      inputDiastolic: e.detail.value
    });
  },

  getPressureStatus: function(systolic, diastolic) {
    if (systolic >= 140 || diastolic >= 90) return '偏高';
    if (systolic < 90 || diastolic < 60) return '偏低';
    return '正常';
  },

  savePressure: function () {
    // 检查输入的血压值是否为空
    if (!this.data.inputSystolic) {
        wx.showToast({
            title: '请输入血压值',
            icon: 'none'
        });
        return;
    }

    // 获取输入的血压值，并转换为数值类型
    const bloodPressure = parseInt(this.data.inputSystolic);

    // 获取当前时间并格式化为 YYYY-MM-DD HH:mm:ss 的形式
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

    // 从本地存储中获取当前用户的 ID
    const userId = wx.getStorageSync('userid');

    // 构建要插入数据库的血压记录对象
    const record = {
        number: bloodPressure, // 血压数值
        typeid: 3, // 血压类型 ID，固定值为 3
        time: formattedTime, // 当前时间
        source: 1, // source 字段，固定值为 1
        userId: userId // 当前用户的 ID
    };

    // 定义数据库插入接口的 URL
    let url = `healthlog/healthlog`;
    // 发送 POST 请求将数据插入数据库
    request({
        url: url,
        method: 'POST',
        data: record,
        success: (res) => {
            // 插入成功时的处理逻辑
            console.log("血压数据插入成功", res.data);
            wx.showToast({
                title: '保存成功',
                icon:'success'
            });
            this.getBloodPressure()
             // 插入成功后重新获取血压列表
             this.getBloodPressure()
             .then(bloodPressure => {
                  this.setData({
                      bloodPressure: bloodPressure
                  });
                  // 获取成功后关闭弹窗并清空输入框
                  this.setData({
                      showModal: false,
                      inputSystolic: ''
                  });
              })
             .catch(error => {
                  console.error("获取血压列表失败", error);
                  wx.showToast({
                      title: '获取血压数据失败',
                      icon: 'none'
                  });
              });
        },
        fail: (error) => {
            // 插入失败时的处理逻辑
            console.error("血压数据插入失败", error);
            wx.showToast({
                title: '保存失败',
                icon: 'none'
            });
        }
        
    });
},    

  editPressure: function(e) {
    const id = e.currentTarget.dataset.id;
    const record = this.data.pressureRecords.find(item => item.id === id);
    if (record) {
      this.setData({
        showModal: true,
        inputSystolic: record.systolic,
        inputDiastolic: record.diastolic
      });
    }
  },

  deletePressure: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除这条记录吗？',
      success: res => {
        if (res.confirm) {
          const pressureRecords = this.data.pressureRecords.filter(item => item.id !== id);
          this.setData({
            pressureRecords
          });
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  }
}); 